package recovery

import (
	"geak/libs/ecode"
	pb_ecode "geak/libs/ecode/pb"
	grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// RecoveryInterceptor panic时返回Unknown错误吗
func RecoveryInterceptor() grpc_recovery.Option {
	return grpc_recovery.WithRecoveryHandler(func(p interface{}) (err error) {
		if err,isok := p.(ecode.Code);isok {
			detail := pb_ecode.From(err)
			s, _ := status.New(codes.FailedPrecondition,err.Message()).WithDetails(
					detail,
				)
			return s.Err()
		}
		return status.Errorf(codes.Unknown, "panic triggered: %v", p)
	})
}